package nsq

import (
	"context"
	"encoding/json"
	dev "ez/apps/dev/document"
	"gitee.com/dreamwood/ez-go/ez"
	"gitee.com/dreamwood/ez-go/maker/mongo"
	"gitee.com/dreamwood/ez-go/ss"
)

func init() {
	ez.Subscribe(ez.EventAfterServerRun, func(v interface{}, ctx context.Context) {
		ez.CreateNsqHandler(ez.EzTopicRegModel, "default", func(content []byte) error {
			doc := new(mongo.Document)
			_ = json.Unmarshal(content, &doc)
			crudModel := dev.NewEzModelCrud()
			find, _ := crudModel.FindOneBy(ss.M{"dir": doc.Path, "name": doc.Name}, nil)
			if find.Id == 0 {
				find.Dir = doc.Path
				find.Name = doc.Name
			}
			find.CnName = doc.CnName
			_ = find.Save()
			find.LoadFields()
			for _, field := range find.Fields {
				_ = field.Destroy()
			}

			for _, field := range doc.Fields {
				fieldSon := new(dev.EzModelField)
				fieldSon.ModelId = find.Id
				fieldSon.Name = field.Name
				fieldSon.CnName = field.CnName
				fieldSon.Type = field.Type
				fieldSon.IsRelation = !(field.JoinDoc == "")
				fieldSon.Src = field.JoinDoc
				_ = fieldSon.Save()
			}

			return nil
		})
	})
}
